package com.houtai.service.activity.apply;

import com.houtai.base.ResultVo;
import com.houtai.bean.TdActivityApply;
import com.houtai.bean.User;
import com.houtai.bean.vo.activity.TdActivityDetail;
import com.houtai.bean.vo.activity.apply.TdActivityApplyInsertDto;
import com.houtai.dao.TdActivityApplyDao;
import com.houtai.dao.TdActivityDao;
import com.houtai.dao.TsJzDictDao;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ActivityApplyService {
    private static Logger logger = Logger.getLogger(ActivityApplyService.class);
    @Autowired
    private TdActivityDao tdActivityDao;
    @Autowired
    private TdActivityApplyDao tdActivityApplyDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Purpose:    活动报名
     * @param:      dto
     * @Version:    1.0
     * @Author:     li
     * @time:       2019/8/21
     * @return:     ResultVo
     */
    public synchronized ResultVo activityApply(TdActivityApplyInsertDto dto, String token) {
        String logInfo = this.getClass().getName() + ":activityApply:";
        ResultVo retInfo = new ResultVo();
        logger.info("======" + logInfo + "begin======");
        try {
            TdActivityDetail tdActivityDetail = tdActivityDao.findTdActivityDetail(dto.getActivity_id());
            if (tdActivityDetail != null) {
                User user = (User)redisTemplate.opsForValue().get(token);
                TdActivityApply tdActivityApply = tdActivityApplyDao.findTdActivityApplyId(user.getUser_id(), dto.getActivity_id());
                if (tdActivityApply != null) {
                    retInfo.setMark("1");
                    retInfo.setTip("已报名该活动");
                } else {

                    tdActivityApply = new TdActivityApply();
                    tdActivityApply.setActivity_id(dto.getActivity_id());
                    tdActivityApply.setApply_name(dto.getApply_name());
                    tdActivityApply.setPhone_no(dto.getPhone_no());
                    tdActivityApply.setUser_id(user.getUser_id());
                    tdActivityApplyDao.insertTdActivityApply(tdActivityApply);
                    tdActivityDetail.setApply_size(tdActivityDetail.getApply_size() + 1);
                    tdActivityDao.updateTdActivityCommentsSize(tdActivityDetail);
                    retInfo.setMark("0");
                    retInfo.setTip("报名成功");
                }
            } else {
                retInfo.setMark("1");
                retInfo.setTip("活动不存在");
            }

        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
